<template>
  <el-tree-select
    v-model="selectValue"
    :clearable="clearable"
    :data="list"
    :disabled="disabled"
    empty-text="暂无数据"
    :multiple="multiple"
    :placeholder="placeholder"
    :readonly="readonly"
    @change="onChange"
  />
</template>
<script setup>
import { postRequest } from "@/api/mains";

const props = defineProps({
  modelValue: {
    type: [Number, String],
    default: ""
  },
  opitionList: {
    type: Array,
    default: () => []
  },
  parmas: {
    type: Object,
    default: undefined
  },
  dictUrl: {
    type: String,
    default: ""
  },
  clearable: {
    type: Boolean,
    default: true
  },
  multiple: {
    type: Boolean,
    default: false
  },
  disabled: {
    type: Boolean,
    default: false
  },
  readonly: {
    type: Boolean,
    default: false
  },
  placeholder: {
    type: String,
    default: ""
  }
});

const emits = defineEmits(["update:model-value"]);
const selectValue = ref(props.modelValue);

const list = ref([]);

const getList = async () => {
  const { dictUrl } = props;

  //  若传入dictUrl则按通过dictUrl获取数据
  if (dictUrl) {
    const { datas } = await postRequest(dictUrl, props.parmas);
    list.value = datas;
  }
};

getList();

const onChange = value => {
  emits("update:model-value", value);
};

watch(
  () => props.opitionList,
  newVal => {
    if (newVal && newVal.length) {
      list.value = newVal;
    }
  },
  {
    deep: true,
    immediate: true
  }
);

watch(
  () => props.modelValue,
  newVal => {
    if (newVal != selectValue.value) {
      selectValue.value = newVal;
    }
  }
);
</script>
<style lang="scss"></style>
